<!-- 商品发布 - 权限设置 -->
<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" :disabled="isDetail">
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>商品权限</span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px">
        无权限浏览则该商品不展示给会员；无购买权限仅支持查看商品，不支持购买商品。
      </span>
    </div>
    <!-- 浏览权限 -->
    <BorwseRuleSelect v-model="formData.browseRuleId" />
    <!-- 购买权限 -->
    <BuyRuleSelect v-model="formData.buyRuleId" />
  </el-form>
</template>
<script lang="ts" setup>
import type { Rule } from '@/api/mall/product/rule'

import { PropType } from 'vue'
import { propTypes } from '@/utils/propTypes'
import { copyValueToTarget } from '@/utils'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import {
  getPropertyList,
  PropertyAndValues,
  RuleConfig
} from '@/views/mall/product/spu/components/index'
import { ProductSkuSetTypeEnum } from '@/utils/constants'
import { BorwseRuleSelect, BuyRuleSelect } from '@/views/mall/product/rule/components/index' //权限
defineOptions({ name: 'ProductPermissionForm' })

const ruleConfig: RuleConfig[] = []
let productQuotaType = getIntDictOptions(DICT_TYPE.PRODUCT_QUOTA_TYPE)
productQuotaType.forEach((ele) => {
  ruleConfig.push({
    name: `${ProductSkuSetTypeEnum.QUOTATYPE.type}${ele.value}`,
    rule: (arg) => arg >= 1,
    message: '商品限购数量必须大于等于 1 ！！！'
  })
})
const message = useMessage() // 消息弹窗

const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  activeName: propTypes.string.def(''),
  isDetail: propTypes.bool.def(false) // 是否作为详情组件
})

const formRef = ref() // 表单Ref
const propertyList = ref<PropertyAndValues[]>([]) // 商品属性列表
const skuListPermissionRef = ref() // 商品属性列表 Ref

// 表单数据
const formData = ref<Rule>({
  browseRuleId: undefined,
  buyRuleId: undefined
})
// 表单规则
const rules = reactive({})

/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }

    copyValueToTarget(formData.value, data)
    // 将 SKU 的属性，整理成 PropertyAndValues 数组
    propertyList.value = getPropertyList(data)
  },
  {
    deep: true,
    immediate: true
  }
)

/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    // 校验 sku
    skuListPermissionRef.value?.validateSku()
    await unref(formRef)?.validate()
    // 校验通过更新数据
    Object.assign(props.propFormData, formData.value)
  } catch (e) {
    message.error('【商品权限】不完善，请填写相关信息')
    emit('update:activeName', 'permission')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })
</script>
